const SqlQuery = reqlib('/lib/sqlquery.js');
const { wx } = require('../../config/config')
// 引入axios
const axios = require('axios')
// // 导出模块对象
module.exports = {
	// 一键登录
	one_click_login: async (ctx, next) => {
		// 获取code 和 用户信息
		const { code } = ctx.request.body
		let nickname = '微信用户'
		let avatar = 'https://picsum.photos/200/200'
		if (code) {
			// 接收到了code就向微信小程序官方发送请求获取openId
			let wxRes = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${wx.appid}&secret=${wx.secret}&js_code=${code}&grant_type=${wx.grant_type}`)
			// 拿到openid和session_key
			const { openid, session_key } = wxRes.data
			// 把openId和用户信息存入数据库，并颁发一个token
			// 查看数据库是否有对应的openid
			if (openid) {
				let [isExe] = await ctx.db.query('select id,nickname,phone ,avatar from users where openid=?', [openid])
				if (isExe.length > 0) {
					return ctx.body = {
						code: 200,
						msg: '登录成功',
						userInfo: isExe[0],
					}
				} else {
					// 不存在
					let [addUser] = await ctx.db.query('insert into users(openid,session_key,nickname,avatar) values(?,?,?,?)', [openid, session_key, nickname, avatar])
					if (addUser.affectedRows >= 1) {
						let [isExe] = await ctx.db.query('select id,nickname,phone ,avatar from users where openid=?', [openid])
						if (isExe.length > 0) {
							return ctx.body = {
								code: 200,
								msg: '登录成功',
								userInfo: isExe[0],
							}
						} 
					}
				}
			} else {
				return ctx.body = {
					code: 500,
					msg: 'openid获取失败'
				}
			}
		}
	},
	// 绑定手机号
	bind_phone: async (ctx, next) => {
		// 获取code 和 用户信息
		const { id, phone } = ctx.request.body
		try {
			let [bindRes] = await ctx.db.query('update users set phone=? where id=?', [phone, id])
			if (bindRes.affectedRows > 0) {
				let [userInfoRes] = await ctx.db.query('select id,nickname,phone ,avatar from users where id=?', [id])
				ctx.body = {
					code: 200,
					msg: '绑定成功',
					userInfo: userInfoRes
				}
				// 返回最新的用户信息
			}
		} catch (error) {
			ctx.body = {
				code: 201,
				msg: '绑定失败' + error.message
			}
		}
	},
	// 管理员登录
    admin_login: async (ctx, next) => {
        const { username, password } = ctx.request.body
		console.log(username, password);
        // 验证用户是否存在
        let [isExit] = await ctx.db.query('select username from admin where username=?', username)
        if (isExit.length <= 0) {
            // 用户不存在
            ctx.body = {
                code: 300,
                msg: '用户不存在'
            }
        } else {
            // 用户存在、获取加密过后的密码
            let [exitRes] = await ctx.db.query('select password from admin where username=?', username)
            // 数据库密码
            let oldPwd = exitRes[0].password
            // 用户发送的密码
            let newPwd = password
            // 如果为true，就是密码正确
            if (oldPwd == newPwd) {
                // 获取用户信息
                let [userInfo] = await ctx.db.query('select id,username from admin where username=?', username)
                return ctx.body = {
                    code: 200,
                    msg: "登陆成功",
                    userInfo:userInfo[0]
                }
            } else {
                // 密码错误
                return ctx.body = {
                    code: 300,
                    msg: "密码错误"
                }
            }
        }
    },
	// 获取用户列表
    get_user_list: async (ctx, next) => {
        
        const {startPage,endPage} = await ctx.service.utils.paging(ctx)
        await ctx.db.query('select * from users where isdel=0 and identity=1').then(async res=>{
            const total =  res[0].length
            await ctx.db.query('select * from users where isdel=0 and identity=1 order by createTime desc limit ?,?',[startPage,endPage]).then(ress=>{
                ctx.body = {
                    code:200,
                    msg:'获取成功',
                    userList:ress[0],
                    total:total
                }
            }).catch(err=>{
                ctx.body = {
                    code:300,
                    msg:'获取失败'+err,
                }
            })
        })
    },
    get_xinli_list: async (ctx, next) => {
        const {startPage,endPage} = await ctx.service.utils.paging(ctx)
        await ctx.db.query('select * from users where isdel=0 and identity=2').then(async res=>{
            const total =  res[0].length
            await ctx.db.query('select * from users where isdel=0 and identity=2 order by createTime desc limit ?,?',[startPage,endPage]).then(ress=>{
                ctx.body = {
                    code:200,
                    msg:'获取成功',
                    userList:ress[0],
                    total:total
                }
            }).catch(err=>{
                ctx.body = {
                    code:300,
                    msg:'获取失败'+err,
                }
            })
        })
    },
    // 根据账号搜索用户
    search_nickname: async (ctx, next) => {
        const {username} = ctx.request.body
        try {
            let [updateRes] = await ctx.db.query(`select * from users where nickname like ?`, [`%${username}%`])
             if(updateRes.length >=1){
                return ctx.body = {
                    code:200,
                    msg:'搜索成功',
                    userList:updateRes
                }
            }else{
                return ctx.body = {
                    code:200,
                    msg:'没有搜索到'
                }
            }
        } catch (error) {
            return ctx.body = {
                code:500,
                msg:'搜索失败'+error
            }
        }
    },
    edit_user: async (ctx, next) => {
        const {id,nickname,identity} = ctx.request.body
        
            try {
                let [updateRes] = await ctx.db.query('update users set nickname=? ,identity=?,updateTime=? where id=?', [nickname,identity,new Date(),id])
                if(updateRes.affectedRows >=1){
                    return ctx.body = {
                        code:200,
                        msg:'修改成功'
                    }
                }else{
                    return ctx.body = {
                        code:300,
                        msg:'修改失败'
                    }
                }
            } catch (error) {
                return ctx.body = {
                    code:500,
                    msg:'修改失败'+error
                }
        }
      
    },
    del_user: async (ctx, next) => {
        const {id} = ctx.request.body
            try {
                let [updateRes] = await ctx.db.query('update users set isDel=1 where id=?', [id])
                if(updateRes.affectedRows >=1){
                    return ctx.body = {
                        code:200,
                        msg:'删除成功'
                    }
                }else{
                    return ctx.body = {
                        code:300,
                        msg:'删除失败'
                    }
                }
            } catch (error) {
                return ctx.body = {
                    code:500,
                    msg:'删除失败'+error
                }
            }
        
       
    },



    // 添加管理员
    ADDADMIN: async (ctx, next) => {
        const { username, password ,identity,nickname} = ctx.request.body
        // 加密密码
        const bcryptPwd = await encryption(password)
        // 创建时间
        let create_time = new Date()
        // 集合注册信息
        const user = [username, bcryptPwd,identity,nickname, create_time]
        // 判断用户是否存在
        const [result] = await db.query('select * from users where username=?', username, (error, results) => {
            if (error) {
                console.log(error.message);
                return ctx.body = {
                    code: 202,
                    msg: '添加失败'
                }
            }
        })
        if (result.length > 0) {
            return ctx.body = {
                code: 202,
                msg: '用户已存在'
            }
        }
        // 进行注册
        const [results] = await db.promise().query('insert into users(username,password,identity,nickname,createTime) values(?,?,?,?,?)', user, (error, results) => {
            if (error) {
                console.log(error.message);
                return
            }
        })
        if (results.affectedRows > 0) {
            ctx.body = {
                code: 200,
                msg: '添加管理员成功'
            }
        }
    },
    // 编辑管理员
    UPDATEUSER: async (ctx, next) => {
        const {id,username,email,nickname,userPic,isDel,identity} = ctx.request.body
        const token = ctx.header.authorization
        let getUserInfo = byTokenInfo(token)
        if(getUserInfo.userInfo.identity == '0'){
           return ctx.body = {
                cpde:300,
                msg:"权限不足"
            }
        }else{
            try {
                let [updateRes] = await db.promise().query('update users set username=?,email=?,nickname=?,userPic=?,isDel=?,identity=?,updateTime=? where id=?', [username,email,nickname,userPic,isDel,identity,new Date(),id])
                if(updateRes.affectedRows >=1){
                    return ctx.body = {
                        code:200,
                        msg:'修改成功'
                    }
                }else{
                    return ctx.body = {
                        code:300,
                        msg:'修改失败'
                    }
                }
            } catch (error) {
                return ctx.body = {
                    code:500,
                    msg:'修改失败'+error
                }
            }
        }
      
    },
    // 删除管理员
    DELUSER: async (ctx, next) => {
        const {id} = ctx.request.body
        const token = ctx.header.authorization
        let getUserInfo = byTokenInfo(token)
        if(getUserInfo.userInfo.identity == '0'){
           return ctx.body = {
                cpde:300,
                msg:"权限不足"
            }
        }else{
            try {
                let [updateRes] = await db.promise().query('update users set isDel=1 where id=?', [id])
                if(updateRes.affectedRows >=1){
                    return ctx.body = {
                        code:200,
                        msg:'删除成功'
                    }
                }else{
                    return ctx.body = {
                        code:300,
                        msg:'删除失败'
                    }
                }
            } catch (error) {
                return ctx.body = {
                    code:500,
                    msg:'删除失败'+error
                }
            }
        }
       
    },
    // 根据账号搜索用户
    SEARCHUSER: async (ctx, next) => {
        const {username} = ctx.request.body
        try {
            let [updateRes] = await db.promise().query(`select id,username,nickname,userPic,isDel,identity ,email from users where username like ?`, [`%${username}%`])
            
             if(updateRes.length >=1){
                return ctx.body = {
                    code:200,
                    msg:'搜索成功',
                    userList:updateRes
                }
            }else{
                return ctx.body = {
                    code:300,
                    msg:'搜索失败'
                }
            }
        } catch (error) {
            return ctx.body = {
                code:500,
                msg:'搜索失败'+error
            }
        }
    },
}